package com.ybbase.framework.config.generator;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.util.*;
import com.ybbase.framework.common.util.FreemarkerUtil;
import com.ybbase.framework.common.util.StringsUtil;

/**
 * 生成Generator
 *
 * @author cg
 */
public class GeneratorMain {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }
    /**
     * 输入业务名称
     * @param businessName
     * @return
     * @author cg
     * @date 2019-11-25 10:34
     * @since 4.0
     */
    public static String businessScanner(String businessName){
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + businessName + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + businessName + "！");
    }

    /**
     * 执行数据
     * @author cg
     * @date 2019-12-10 17:28
     * @since cloud2.0
    */
    public static void main(String[] args) throws Exception {
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor(scanner("作者"));
        String businessName = businessScanner("请输入业务名称，请不要输入/");
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // set freemarker engine
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 全局配置
        String projectPath = System.getProperty("user.dir") + GeneratorServiceStaticParam.INFRASTRUCTURE;
        /**
         * 需要配置生成服务的名称
         * */
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setOpen(false);
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        //实体属性 Swagger2 注解
        gc.setSwagger2(true);
        gc.setFileOverride(true);
        // 不需要ActiveRecord特性的请改为false
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/largedeposit?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("Chen_3811630");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.ybbase.framework");
        pc.setController("controller"+(StringUtils.isNotEmpty(businessName)?"."+businessName:""));
        pc.setEntity("model.po"+(StringUtils.isNotEmpty(businessName)?"."+businessName:""));
        pc.setMapper("mapper"+ (StringUtils.isNotEmpty(businessName)?"."+businessName:""));
        pc.setServiceImpl("service"+ (StringUtils.isNotEmpty(businessName)?"."+businessName+".":"")+"impl");
        pc.setService("service"+ (StringUtils.isNotEmpty(businessName)?"."+businessName:""));
        mpg.setPackageInfo(pc);
        // 自定义配置
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            //自定义属性注入:abc
            //在.ftl(或者是.vm)模板中，通过${cfg.abc}获取属性
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("businessName", businessName);
                this.setMap(map);
            }
        };
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        String templatePath = "/templates/mapper.xml.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/"+(StringUtils.isNotEmpty(businessName)?businessName+"/":"")+
                        tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setEntity("/vmtemplates/templateEntity.java");
        templateConfig.setController("/vmtemplates/templateController.java");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setTablePrefix("sys_");
        List<TableFill> tableFills = new ArrayList<>();
        tableFills.add(new TableFill("create_by", FieldFill.INSERT));
        tableFills.add(new TableFill("create_date", FieldFill.INSERT));
        tableFills.add(new TableFill("update_by", FieldFill.INSERT_UPDATE));
        tableFills.add(new TableFill("update_time", FieldFill.INSERT_UPDATE));
        strategy.setTableFillList(tableFills);
        strategy.setLogicDeleteFieldName("del_flag");
        // 公共父类
        strategy.setSuperControllerClass("com.ybbase.framework.base.controller.BaseController");
        // 写于父类中的公共字段
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        // 生成错误验证码
        String [] tables= strategy.getInclude();
        Map<String, Object> root = new HashMap<String, Object>();

        String codePath =projectPath+"/src/main/resources/errorcode/"+businessName+"/";
        for (String table:tables){
            String name= StringsUtil.getClassName(table);
            FreemarkerUtil.printFile("templateErrorcode.vm", root, name.toLowerCase()+".properties", codePath, "vmtemplates/");
        }

        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());

        try{
            mpg.execute();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}